import { useEffect, useRef, useState, useImperativeHandle } from 'react';

export default (props, ref) => {
  const { end, start = 0, speed = 50 } = props;
  const [text, setText] = useState(start);
  const pre = usePrevious({ text });
  useEffect(() => {
  }, [])

  useImperativeHandle(props.onRef, () => {
    return {
      start: calc,
      reset: reset,
      text: text
    };
  });

  function reset() {
    setText(0)
  }

  function calc() {
    if (pre.current.text === end) {
      pre.current.text = 0
    }
    let timer = setInterval(() => {
      let t = pre.current.text + 1;
      if (t > end) {
        clearTimeout(timer);
        return
      }
      setText(t)
    }, speed)
  }

  return (
    <span>{text}</span>
  )
}

function usePrevious(value) {
  const ref = useRef({})
  useEffect(() => {
    ref.current = value
  })
  return ref
}